package com.sunlands.zlcx.usercenter.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sunlands.zlcx.usercenter.config.ClientConfig;
import com.sunlands.zlcx.usercenter.util.BeanPropertiesUtil;
import com.sunlands.zlcx.usercenter.util.HttpUtil;
import com.sunlands.zlcx.usercenter.vo.AccessTokenVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpException;
import org.springframework.data.util.Pair;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * @author anjl
 * 用于处理用户登录相关的service
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements  BeanPropertiesUtil {

    public AccessTokenVO getPasswordToken(String username, String password) {
        Map<String, String> headers = new HashMap<>(1);
        headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);

        Map<String, Object> bodyMap = new HashMap<>(3);
        bodyMap.put("grant_type", "password");
        bodyMap.put("username", username);
        bodyMap.put("password", password);

        String response;
        try {
            response = HttpUtil.doPost(clientConfig.getTokenUri(), headers, Pair.of(clientConfig.getClientId(), clientConfig.getClientSecret()), bodyMap);
            log.debug("response={}", response);
            return objectMapper.readValue(response, AccessTokenVO.class);
        } catch (HttpException e) {
            log.error("登录失败", e);
            throw new IllegalArgumentException("登录失败! 请确认用户名和密码是否正确");
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public AccessTokenVO refreshToken(String refreshToken) {
        Map<String, String> headers = new HashMap<>(1);
        headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);

        Map<String, Object> bodyMap = new HashMap<>(3);
        bodyMap.put("grant_type", "refresh_token");
        bodyMap.put("refresh_token", refreshToken);
        String response;
        try {
            response = HttpUtil.doPost(clientConfig.getTokenUri(), headers, Pair.of(clientConfig.getClientId(), clientConfig.getClientSecret()), bodyMap);
            log.debug("response={}", response);
            return objectMapper.readValue(response, AccessTokenVO.class);
        } catch (HttpException e) {
            log.error("", e);
            throw new IllegalArgumentException("刷新token失败！");
        }catch (IOException e) {
            log.error("", e);
            return null;
        }
    }

    private final ObjectMapper objectMapper;
    private final ClientConfig clientConfig;
    public UserDetailsServiceImpl(ObjectMapper objectMapper, ClientConfig clientConfig) {
        this.objectMapper = objectMapper;
        this.clientConfig = clientConfig;
    }

}
